package com.lineng.service.impl;

import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lineng.dao.UserMapper;
import com.lineng.pojo.User;
import com.lineng.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	UserMapper userMapper;

	@Autowired
	private HttpServletRequest request;

	public int register(String username, String password) {
		String permission = (String) request.getSession().getAttribute("permission");
		int num = 0;
		// 判断用户是否有权限添加用户
		if ("0".equals(permission)) {
			if (username != null && password != null) {
				if (userMapper.selectUserByUsername(username) != null) {
					return 0;
				}
				User user = new User();
				user.setId(UUID.randomUUID().toString());
				user.setUsername(username);
				user.setPassword(password);
				user.setPermission("1");
				num = userMapper.insertSelective(user);
				return num;
			}
		}
		return 2;

	}

	public List<User> getUser() {
		List<User> users = null;
		String permission = (String) request.getSession().getAttribute("permission");
		if ("0".equals(permission)) {
			users = userMapper.selectUserByPermission("1");
		}

		return users;

	}

	public User getUserById(String username) {
		return userMapper.selectUserByUsername(username);
	}

	public int deleteUser(String id) {
		String permission = (String) request.getSession().getAttribute("permission");
		if ("0".equals(permission)) {
			return userMapper.deleteByPrimaryKey(id);
		}
		return 0;
	}

	public int updateUser(String id, String password) {
		String permission = (String) request.getSession().getAttribute("permission");
		if ("0".equals(permission)) {
			User user = new User();
			user.setPassword(password);
			user.setId(id);
			return userMapper.updateByPrimaryKeySelective(user);
		}
		return 0;

	}

}
